// AI 状态指示器组件

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { FiWifi, FiWifiOff, FiAlertCircle } from 'react-icons/fi';
import { aiService } from '../services/aiService';

interface AIStatusProps {
  className?: string;
}

const AIStatus: React.FC<AIStatusProps> = ({ className = '' }) => {
  const [status, setStatus] = useState<'checking' | 'connected' | 'disconnected'>('checking');
  const [lastCheck, setLastCheck] = useState<Date | null>(null);

  useEffect(() => {
    checkAIStatus();
    // 每分钟检查一次
    const interval = setInterval(checkAIStatus, 60000);
    return () => clearInterval(interval);
  }, []);

  const checkAIStatus = async () => {
    try {
      setStatus('checking');
      const isHealthy = await aiService.healthCheck();
      setStatus(isHealthy ? 'connected' : 'disconnected');
      setLastCheck(new Date());
    } catch (error) {
      setStatus('disconnected');
      setLastCheck(new Date());
    }
  };

  const getStatusInfo = () => {
    switch (status) {
      case 'checking':
        return {
          icon: FiWifi,
          text: '检查中...',
          color: 'text-yellow-500',
          bgColor: 'bg-yellow-500/20'
        };
      case 'connected':
        return {
          icon: FiWifi,
          text: 'AI 已连接',
          color: 'text-green-500',
          bgColor: 'bg-green-500/20'
        };
      case 'disconnected':
        return {
          icon: FiWifiOff,
          text: 'AI 未连接',
          color: 'text-red-500',
          bgColor: 'bg-red-500/20'
        };
    }
  };

  const statusInfo = getStatusInfo();
  const Icon = statusInfo.icon;

  return (
    <motion.div 
      className={`flex items-center gap-2 px-3 py-2 rounded-lg ${statusInfo.bgColor} ${className}`}
      initial={{ opacity: 0, scale: 0.9 }}
      animate={{ opacity: 1, scale: 1 }}
      whileHover={{ scale: 1.02 }}
      onClick={checkAIStatus}
      role="button"
      title={`点击刷新状态${lastCheck ? ` • 最后检查: ${lastCheck.toLocaleTimeString()}` : ''}`}
    >
      <motion.div
        animate={{ 
          rotate: status === 'checking' ? 360 : 0,
          scale: status === 'checking' ? [1, 1.2, 1] : 1
        }}
        transition={{ 
          duration: status === 'checking' ? 1 : 0.2,
          repeat: status === 'checking' ? Infinity : 0,
          ease: "easeInOut"
        }}
      >
        <Icon className={`w-4 h-4 ${statusInfo.color}`} />
      </motion.div>
      
      <span className={`text-sm font-medium ${statusInfo.color}`}>
        {statusInfo.text}
      </span>
      
      {status === 'disconnected' && (
        <FiAlertCircle className="w-3 h-3 text-red-400" />
      )}
    </motion.div>
  );
};

export default AIStatus;
